<?php

namespace app\notify\controller;

use Throwable;
use think\Response;
use app\BaseController;
use think\exception\HttpResponseException;
use ball\WechatApp;
use think\Exception;
use app\common\model\Payment;
use think\facade\Log;

/**
 * API控制器基类
 */
class Notify extends BaseController
{
    
    
    /**
     * 控制器初始化方法
     * @access protected
     * @throws Throwable
     */
    protected function initialize(): void
    {
        // 系统站点配置
        set_timezone(); // 时区设定
        parent::initialize();
    }

    public function index(){
        Log::info(json_encode($this->request->param()));
        $client_sn = $this->request->param('client_sn');
        try {
            $result = "success";
            $code="200";
            if(empty($client_sn)){
                $notify =  WechatApp::notify();
                if($notify === false){
                    throw new Exception('error');
                }
                $client_sn = $notify['out_trade_no'];
                $result = ["code"=> "SUCCESS","message"=> "成功"];
                $code="200";
            }
            $payInfo = Payment::verify($client_sn);
            if($payInfo ===  false){
                throw new Exception('error');
            }

        } catch (\Throwable $th) {
            if(empty($client_sn)){
                $result = ["code"=> "FAIL","message"=> "失败"];
                $code="400";
            }else{
                $code="400";
                $result='fail';
            }
        }
        $response = Response::create($result, 'json', $code);
        throw new HttpResponseException($response);

    }
    /**
     * 退款
     */
    public function refund(){

    }
}